<?php
namespace app\api\controller\v2;
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/8/7
 * Time: 11:23
 */

use app\services\car\OrderPayServices;
use think\log;
use crmeb\services\SpreadsheetExcelService;
use app\Request;
use crmeb\services\app\MiniProgramService;
use crmeb\services\app\WechatService;
use app\api\controller\v3\WxPayController as v3WxPayController;
use app\api\controller\v3\SampleController;
use think\facade\Db;
use app\api\controller\v2\LogController;
use stdClass;
use app\services\pay\SmfpayServices;
use app\services\other\UploadService;
use think\facade\Cache;
class SmfController
{

    protected $key = NULL;
    protected $message_key = NULL;
    protected $services = NULL;
    protected $mercCode = NULL;
    protected $agentCode = NULL;

    public function __construct()
    {
        $this->key = "lbWecTu0Zjvi4b18WkBndO3bzkdp7GTKNYau2jG4csEw8HHoyuDt8aJKCOv8QCvb"; // 签名密钥
        $this->message_key = "J1BbO69F"; // 报文密钥
        $this->mercCode = 'MER0000000003942';//商户号
        $this->agentCode = 'AGT0000000000582';//代理商号
        $this->url='https://smf.jingweitech.cn:8443';//正式环境

//        $this->key = "P6JafGO9QU2fTyASvyyD0KXHsnsokw3sh7Vx1obA6ygAiAoLsjwxThjfLCyXvatI"; // 签名密钥
//        $this->message_key = "KRH9keYRyuVuRVm0LNMQoEX7qSDISv5VMgYHe3gL87wkmUQIY2F1NsCnAWX7oYvQ"; // 报文密钥
//        $this->mercCode = 'MER0000000003942';//商户号
//        $this->agentCode = 'AGT0000000000171';//代理商号
//        $this->subProCode='1740291488769773';//子产品编号
//        $this->url='http://test.app.jingweitech.cn:8280';//测试环境


    }
    //#扫码付
    public function smfpay(){
        $config1['outTradeNo'] = time()."2wdeqwd";
        $config1['mercCode'] = 'AGT0000000000582';//商户号
        $config1['orderAmount'] = '0.01';//金额
        $config1['clientType'] = 'APP';
        $config1['tradeDesc'] = '订单说明';
        $notify_url = 'https://pay.****.com/Payment/notifysmf'; // 接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。
        $config1['notifyUrl'] = $notify_url;
        $config1['termIp'] = $this->get_client_ip();//IP
        $config1['frontNotifyUrl'] = 'https://pay.test.com/Order/order_list/';//前端支付成功后跳转路径
        $saccPayeeList []= ['saccPayeeCode'=>'11111','saccAmount'=>15];//分账收款方列表
        $config2 = new stdClass();//声明空对象
        $config2->saccInfo = ['saccWay'=>"SYNC",'saccValidDay'=>1,'saccNotifyUrl'=>'http://ttt.com','saccPayeeList'=>$saccPayeeList];//分账信息
        $config['nonce'] = time();
        $config['platformMercCode'] = 'AGT0000000000582'; //平台商户号
        $config['reqData'] = stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE));
        $sing = $this->ASCIISHA256($config, 'bWecTu0Zivi4b18WkBnd03bzkdp7GTKNYau2iG40sEw8HHoyuDt8aJKCOv80Cvb');
        $config['sign'] = $sing;
        $config['reqData'] = $this->encryptStr(stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE)), 'J1BbO69F');
        $headers = [ 'Content-Type: application/json; charset=utf-8'];
        $res = http_post_json($this->url."/api/trade/cashierPreOrder.html", json_encode($config, JSON_UNESCAPED_UNICODE),$headers);
        $pay_res = json_decode($res, true);
        if ($pay_res['respMsg'] == '成功') {
        } else {
            echo '调起支付失败';
        }
    }
    //#扫码付退款
    public function smf_refund(Request $request){
        $data = $request->postMore([
            ['appid','1'],
            ['payOutTradeNo'],//合作方支付订单号
            ['outTradeNo'],//合作方系统的退款订单号
            ['refundAmount'],//退款金额
            ['refundRemark'],//退款说明
        ]);
        if(!$data['payOutTradeNo']||!$data['outTradeNo']||!$data['refundAmount']||!$data['appid'])return app('json')->fail('缺少参数');
        $pay = new SmfpayServices();
        $code = $pay->smf_refund($data);
        return app('json')->success("获取成功",$code);

    }

    /*
     * 扫码富商户进件
     * */
    public function smf_subApplyment()
    {
        $json = file_get_contents('php://input');
        if(!$json)return app('json')->fail('缺少参数');
        $data = json_decode($json,true);//json转数组
        $smf = new SmfpayServices();
        $smf->smf_subApplyment($data);
    }


    /**
     * 扫码富获取行业编号
     */
    public function get_smf_mcc(Request $request)
    {
        $smf = new SmfpayServices();
        $data = $smf->get_smf_mcc();
        return app('json')->success("获取成功",$data);

    }
    /**
     * 扫码富获取银行编号
     */
    public function get_bank_code(Request $request)
    {
        $smf = new SmfpayServices();
        $data = $smf->get_bank_code();
        return app('json')->success("获取成功",$data);
    }

    /*
    * 根据银行编号查询该银行下面所有支行信息
    * */
    public function get_bank_branch(Request $request){
        $data = $request->getMore([
            ['page',1],
            ['bank_id',''],
            ['sub_branch_no',''],
            ['sub_branch_name',''],
            ['prov_code']
        ]);
        if(!$data['bank_id']||!$data['prov_code'])return app('json')->fail('参数错误');
        $smf = new SmfpayServices();
        $data = $smf->get_bank_branch($data);
        return app('json')->success("获取成功",$data);
    }

    //省市区编码
    public function get_smf_city_code(){
        $smf = new SmfpayServices();
        $data = $smf->get_smf_city_code();
        return app('json')->success($data);
    }

    //扫码富获取图片下载地址
    public function getImageDownloadUrl(Request $request){
        $data = $request->getMore([
            ['imageCode',''],
        ]);
        if(!$data['imageCode'])return app('json')->fail('参数错误');
        $smf = new SmfpayServices();
        $data = $smf->getImageDownloadUrl($data);
        return app('json')->success($data);
    }


    //根据会员id查询商户审核结果
    public function queryCheckResult(Request $request){
        $data = $request->getMore([
            ['uid',''],
        ]);
        if(!$data['uid'])return app('json')->fail('参数错误');
        $smf = new SmfpayServices();
        $data = $smf->queryCheckResult($data);
        return app('json')->success($data);
    }
    /*
     * 发起签约
     * 商户进件且通道需要签约，通过此接口发起签约。签约状态为待签约，才能发起签约。
     * */
    public function smf_Sign(Request $request){
        $data = $request->getMore([
            ['applyOrderNo',''],
        ]);
        if(!$data['applyOrderNo'])return app('json')->fail('参数错误');
        $smf = new SmfpayServices();
        $data = $smf->smf_Sign($data);
        return app('json')->success($data);
    }
    //校验签约短信
    public function verifySignedSms(Request $request){
        $data = $request->getMore([
            ['applyOrderNo',''],
            ['smsCode','']
        ]);
        if(!$data['applyOrderNo']||!$data['smsCode'])return app('json')->fail('参数错误');
        $smf = new SmfpayServices();
        $data = $smf->verifySignedSms($data);
        return app('json')->success($data);
    }
    //获取实名认证信息
    public function getRealNameAuthInfo(Request $request){
        $data = $request->getMore([
            ['mercCode',''],
            ['processId','']
        ]);
        if(!$data['mercCode'])return app('json')->fail('参数错误');
        $smf = new SmfpayServices();
        $data = $smf->getRealNameAuthInfo($data);
        return app('json')->success($data);
    }

    //根据商户号查询扫码富余额
    public function  queryBalance(Request $request){
        $data = $request->getMore([
            ['mercCode',''],
        ]);
        if(!$data['mercCode'])return app('json')->fail('参数错误');
        $smf = new SmfpayServices();
        $data = $smf->queryBalance($data);
        return app('json')->success($data);
    }

        //手动推送数据到约你游商户
    public function post_ynyvendor(Request $request)
    {
        $data = $request->getMore([
            ['uid',''],
        ]);
        if(!$data['uid'])return app('json')->fail('参数错误');
        $smf = new SmfpayServices();
        $smf->post_ynyvendor($data);
    }

    //手动推送数据到约你游商户
    public function post_ynyvendor2(Request $request)
    {
        $data = $request->getMore([
            ['uid',''],
        ]);
        if(!$data['uid'])return app('json')->fail('参数错误');
        $smf = new SmfpayServices();
        $smf->post_ynyvendor2($data);
    }
    /*
    /**
     * ASCII排序
     * @param array $params
     * @param $key
     * @return bool|string
     */
   public function ASCIISHA256($params = array(), $key)
    {
        if (!empty($params)) {
            $params = array_filter($params);
            $p = ksort($params);
            if ($p) {
                $str = '';
                foreach ($params as $k => $val) {
                    $val = trim($val);
                    if ($val === '' || $val === null) {
                        continue;
                    }
                    $str .= $k . '=' . $val . '&';
                }
                $strs = rtrim($str, '&');
                $stringSignTemp = $strs . '&key=' . $key;


                $re = hash('sha256', $stringSignTemp, true);
                return strtoupper(bin2hex($re));
            }
        }
        return false;
    }


    /**
     * des 加密
     * str 需要加密的账号
     * key 加密秘钥
     */
    public function encryptStr($str, $key)
    {
        $data = mb_convert_encoding($str, 'UTF-8');
        $encry = openssl_encrypt($data, 'DES-ECB', $key, OPENSSL_RAW_DATA);
        return base64_encode($encry);
    }

    /**
     * 解密
     */
    public function decryptStr($data, $key)
    {
        $decry = openssl_decrypt(base64_decode($data), 'DES-ECB', $key, OPENSSL_RAW_DATA);
        return $decry;
    }

    //获取ip
    function get_client_ip(){
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")){
            $ip = getenv("HTTP_CLIENT_IP");
        }else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")){
              $ip = getenv("HTTP_X_FORWARDED_FOR");
        }else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")){
            $ip = getenv("REMOTE_ADDR");
        }else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")){
            $ip = $_SERVER['REMOTE_ADDR'];
        }else{
            $ip = "unknown";

        }
        return($ip);
    }

    /**
     * 扫码富特约商户上传图片获取OSS上传凭证
     */
    public function mediaUpload(Request $request)
    {
        $data = $request->postMore([
            ['imageFormat',''],
            ['imageType',''],
        ]);
        if(!$data['imageFormat']||!$data['imageType'])return app('json')->fail('参数错误');
        $config1['imageFormat'] = $data['imageFormat'];
        $config1['imageType'] = $data['imageType'];
        $config['nonce'] = time();
        $config['agentCode'] = $this->agentCode; //代理商号
        $config['reqData'] = stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE));
        $sing = $this->ASCIISHA256($config, $this->key);
        $config['sign'] = $sing;
        $config['reqData'] = $this->encryptStr(stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE)), $this->message_key);
        //https://smf.jingweitech.cn:8443/api/other/getOssUploadInfo.html
        $res = http_post_json($this->url."/api/other/getOssUploadInfo.html", $config,['Content-Type: application/json; charset=utf-8']);//正式
        if($res['respMsg']!="成功")return app('json')->fail($res['respMsg']);
        //解密
        $res = $this->decryptStr($res['respData'],$this->message_key);
        $res = json_decode($res,true);
        return app('json')->success($res);
    }

    //支付订单结果查询
    public function queryPayOrder(Request $request){
        $data = $request->postMore([
            ['outTradeNo',''],
        ]);
        $config1['outTradeNo'] = $data['outTradeNo'];
        $config['nonce'] = time();
        $config['agentCode'] = $this->agentCode; //代理商号
        $config['reqData'] = stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE));
        $sing = $this->ASCIISHA256($config, $this->key);
        $config['sign'] = $sing;
        $config['reqData'] = $this->encryptStr(stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE)), $this->message_key);
        //https://smf.jingweitech.cn:8443/api/other/getOssUploadInfo.html
        $res = http_post_json($this->url."/api/trade/queryPayOrder.html", $config,['Content-Type: application/json; charset=utf-8']);//正式
        if($res['respMsg']!="成功")return app('json')->fail($res['respMsg']);
        //解密
        $res = $this->decryptStr($res['respData'],$this->message_key);
        $res = json_decode($res,true);
        return app('json')->success($res);
    }

}